<script setup>
import * as THREE from 'three'
// 引入轨道控制器
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'

// 创建场景、相机和渲染器
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
camera.position.z = 5

const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.shadowMap.enabled = true // 启用阴影渲染
document.body.appendChild(renderer.domElement)

// 添加环境光
const ambientLight = new THREE.AmbientLight(0x404040, 0.5)
scene.add(ambientLight)

// 添加平行光并启用阴影
const directionalLight = new THREE.DirectionalLight(0xffffff, 1)
directionalLight.position.set(5, 10, 7.5)
directionalLight.castShadow = true
directionalLight.shadow.mapSize.width = 1024
directionalLight.shadow.mapSize.height = 1024
scene.add(directionalLight)

// 创建地面并使其接收阴影
const planeGeometry = new THREE.PlaneGeometry(200, 200)
const planeMaterial = new THREE.MeshStandardMaterial({ color: 0x808080 })
const plane = new THREE.Mesh(planeGeometry, planeMaterial)
plane.rotation.x = - Math.PI / 2
plane.position.y = -1
plane.receiveShadow = true
scene.add(plane)

// 创建一个立方体并使其投射阴影
const cubeGeometry = new THREE.BoxGeometry(1, 1, 1)
const cubeMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000 })
const cube = new THREE.Mesh(cubeGeometry, cubeMaterial)
cube.position.y = 0.5
cube.castShadow = true
scene.add(cube)

// 创建轨道控制器
const controls = new OrbitControls(camera, renderer.domElement)
// 开启阻尼系数
controls.enableDamping = true
// 设置阻尼系数
controls.dampingFactor = 0.05

// 动画循环
function animate() {
  requestAnimationFrame(animate)
  controls.update()
  cube.rotation.x += 0.01
  cube.rotation.y += 0.01

  renderer.render(scene, camera)
}

animate()
</script>

<template>
  <div></div>
</template>

<style scoped></style>\